import csv
import os

from flask import Flask, request, jsonify

app = Flask(__name__)

# 文件路径
USER_FILE = "users.csv"

# 初始化 CSV 文件
if not os.path.exists(USER_FILE):
    with open(USER_FILE, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(["username", "password", "usertype"])  # 添加表头
        writer.writerow(["admin", "admin123", 0])  # 默认管理员用户


# 读取用户数据
def read_users():
    with open(USER_FILE, mode='r') as file:
        reader = csv.DictReader(file)
        return list(reader)


# 写入用户数据
def write_users(users):
    with open(USER_FILE, mode='w', newline='') as file:
        fieldnames = ["username", "password", "usertype"]
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(users)


@app.route('/add_person', methods=['POST'])
def add_person():
    data = request.json
    username = data.get("username")  # 前端发送的字段为 username
    password = data.get("password")  # 前端发送的字段为 password

    if not username or not password:
        return jsonify({"error": "用户名和密码不能为空"}), 400

    users = read_users()
    if any(user["username"] == username for user in users):
        return jsonify({"error": "人员已存在"}), 400

    # 添加人员，默认权限为0
    users.append({"username": username, "password": password, "usertype": 0})
    write_users(users)
    return jsonify({"message": "人员添加成功"}), 201


# 登录
@app.route('/login', methods=['POST'])
def login():
    print("/login")
    data = request.json
    print(data)
    username = data.get("username")
    password = data.get("password")

    users = read_users()
    user = next((user for user in users if user["username"] == username and user["password"] == password), None)

    if user:
        # 构造响应数据
        response_data = {
            "message": "登录成功",
            "data": {
                "username": user["username"],
                "usertype": user["usertype"],
                # "token": "example-token"  # 示例 token，可替换为真实生成的 token
            }
        }
        return jsonify(response_data), 200
    else:
        return jsonify({"error": "用户名或密码错误"}), 401


# 获取所有用户
@app.route('/users', methods=['GET'])
def get_users():
    users = read_users()
    personnel_data = [
        {"name": user["username"], "group": user.get("group", "未分组"), "usertype": user.get("usertype", "0")}
        for user in users
    ]
    return jsonify(personnel_data), 200


# 删除用户
@app.route('/users/<username>', methods=['DELETE'])
def delete_user(username):
    users = read_users()
    users = [user for user in users if user["username"] != username]
    write_users(users)
    return jsonify({"message": "用户已删除"}), 200


# 权限修改
@app.route('/users/<username>', methods=['PUT'])
def update_user(username):
    data = request.json
    new_usertype = data.get("usertype")

    if new_usertype is None:
        return jsonify({"error": "未提供新的权限级别"}), 400

    users = read_users()
    for user in users:
        if user["username"] == username:
            user["usertype"] = new_usertype
            write_users(users)
            return jsonify({"message": "用户权限已更新"}), 200

    return jsonify({"error": "用户不存在"}), 404

# 启动服务器
if __name__ == '__main__':
    app.run(debug=True)
